package com.hummingbird.portal.controller;


import com.hummingbird.portal.dto.AnswerDTO;
import com.hummingbird.portal.pojo.Answer;
import com.hummingbird.portal.r.R;
import com.hummingbird.portal.service.IAnswerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author -1E18
 * @since 2024-09-22
 */
@RestController
@RequestMapping("/portal/answer")
@Slf4j
public class AnswerController {
    @Resource
    private IAnswerService answerService;

    @PostMapping
//只有老师能回答问题,所以限制有回答权限或者有老师身份的人才能运行这个方法
//@PreAuthorize("hasAuthority('/question/answer')")
    @PreAuthorize("hasRole('TEACHER')")
    public R postAnswer(
            @Validated AnswerDTO answerDTO, BindingResult result,
            @AuthenticationPrincipal UserDetails user
    ) {
        log.debug("接收到信息:{}",answerDTO);
        if (result.hasErrors()) {
            String msg=result.getFieldError().getDefaultMessage();
            return R.unproecsableEntity(msg);
        }
        Answer answer = answerService
                .saveAnswer(answerDTO,user.getUsername());
        return R.created("添加回答完成");
    }

    @GetMapping("question/{questionId}")
    public R questionAnswers(@PathVariable Integer questionId) {
        List<Answer> answers = answerService.getAnswersByQuestionId(questionId);

        return R.ok(answers);
    }
}
